<?php
/**
 * Created by PhpStorm.
 * User: 65736
 * Date: 2019/3/13 0013
 * Time: 17:09
 */

namespace app\common\widget;


class WidgetRadio extends WidgetInput
{
    /**
     * Radio 列表数组 [数组key为radio的value] [数组value为radio的显示名称]
     * @var array
     */
    private $radioList=[];

    /**
     * Radio input Html 集合
     * @var array
     */
    private $raidoInputList = [];

    /**
     * 构造方法, 渲染挂件
     * @return mixed
     * @throws \think\Exception
     */
    function render()
    {
        // 创建表单数据
        $this->createRadioInput();
        // 分配数据
        self::$view->assign('radioInputList', $this->raidoInputList);
        return $this->fetch();
    }

    /**
     * @return $this
     * @throws \think\Exception
     * @throws \Exception
     */
    private function createRadioInput() {
        // 检测
        if ( !$this->radioList ) $this->throwException("Radio挂件数据为空");
        // 获取id和name
        $id = $this->getId();
        $name = $this->getName();
        $domAttrs = $this->domAttrs;
        // 创建
        foreach ( $this->radioList as $key=>$value ) {
            if ( !$id )  {
                $_id = "radio_{$name}_{$key}";
            }else{
                $_id = "radio_{$name}_{$id}";
            }
            // 表单对象
            $input = new WidgetInput();
            // 设置表单对象
            $input->setDomAttrList($domAttrs)
                ->setInputType(parent::inputTypeRadio)
                ->setClass( $this->getClass() )
                ->remClass( self::defaultClass )
                ->setValue( $key )
                ->setId($_id);
            if ( $name )  $input->setName( $name );
            // 设置选中
            $_value = $this->getValue();
            if ( ''!==$_value && $key == $_value ) $input->setDomAttr("checked", "checked");

            // 生成数据
            $html = $input->render();
            $html .= $value;
            $html = "<div class='radio'><label>{$html}</label></div>";
            $this->raidoInputList[] = $html;
        }
        return $this;
    }


    /**
     * 设置Radio列表
     * @param array $radioList 列表数组 [数组key为radio的value] [数组value为radio的显示名称]
     * @return $this
     * @throws \think\Exception
     */
    public function setRadioList( array $radioList ) {
        if ( !$radioList ) $this->throwException("Radio列表错误");
        $this->radioList = $radioList;
        return $this;
    }

    /**
     * 获取Radio列表
     * @return array
     */
    public function getRadioList(): array
    {
        return $this->radioList;
    }

    /**
     * 获取raidoInputList
     * @return array
     */
    public function getRaidoInputList(): array
    {
        return $this->raidoInputList;
    }


}